package cn.mugutu.finance.listener;

import cn.mugutu.finance.domain.system.Log;
import cn.mugutu.finance.enums.LogTyep;
import cn.mugutu.finance.service.system.InitService;
import cn.mugutu.finance.service.system.LogService;
import cn.mugutu.finance.task.AwardTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Date;

@WebListener
@Slf4j
public class Installer implements ServletContextListener {

    private WebApplicationContext beans;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            log.info("系统启动开始初始化系统基本数据...");
            beans = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
            InitService initService = beans.getBean(InitService.class);
            initService.initSysBaseData();

            beans.getBean(AwardTask.class).run(); //每次启动去拉取一次新增的双色球数据
            log.info("系统启动拉取双色球新增最新数据完毕.");
            log.info("<==系统基本数据初始化完毕==>");
        } catch (Exception e) {
            log.error("初始化系统失败,失败信息=========>");
            e.printStackTrace();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("正在关闭服务器....");
        LogService logService = beans.getBean(LogService.class);
        Log log = new Log();
        log.setOperTime(new Date());
        log.setDescription("关闭服务器.");
        log.setLogTyep(LogTyep.BUSINESSLOG);
        logService.save(log);
    }

}
